""" 

    Main.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
        
    This service generates the main page that you see in RepresentedBy.  There are several handlers that are used for
    alternate views of the page (e.g. state only, district only).  These were used in earlier version of RepresentedBy,
    but have been removed from the tab navigation so you can only see them now by URL hacking.
    
    If a user is not logged into Facebook, they will be redirected to the page asking them to add
    the app and/or login to Facebook.
    
    This page only works with a post() so querying the URL directly will not return anything.
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import math
import string

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserDistrict, SunlightUtil, OpenSecretsUtil, NYTimesUtil
from sets import Set
            
class MainHandler(webapp.RequestHandler):

    def post(self):
        try:
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, True, "")
            if self.facebookapi is None:
                return
            
            redirect = fbUtil().getRedirect(int(self.facebookapi.uid))
            if redirect is not None:
                self.response.out.write('<fb:redirect url="http://apps.facebook.com/representedby/' + redirect + '" />')
                return
         
            user = self.facebookapi.users.getInfo([self.facebookapi.uid], ['uid', 'name', 'current_location'])[0]
            userInfo = dbUtil().getLegislatorForUser(user["uid"], user["current_location"], True)
            if userInfo is None:
                self.response.out.write('<fb:redirect url="/representedby/location" />')
            else:    
                userInfo["section"] = "main"
                userInfo["discussion_board"] = {"id": "", "name": "your legislators", "modifier": "with"}
                userInfo["loggedin"] = True
                if not userInfo.has_key("rep"):
                    userInfo["rep"] = "BLANK"
                output = PageCreator()
                output.render(self, userInfo)
                
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working"}))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)})) 
            
            
class Legislator(webapp.RequestHandler):
    def post(self):
        legislator_id = self.request.get('id', default_value=None)
        if legislator_id is None:
            self.response.out.write('<fb:redirect url="/representedby/legislators" />')
        else:
            try:
                userInfo = {"section": "legislators", "legislator":legislator_id, "discussion_board" : {"id": legislator_id, "name": "this legislator", "modifier": "with"}}
                self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
                if self.facebookapi is None:
                    userInfo["loggedin"] = False
                else:
                    userInfo["loggedin"] = True
                output = PageCreator()
                output.render(self, userInfo)
            except urlfetch.DownloadError, e:
                path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
                self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working - " + str(e.msg)}))
            except facebook.FacebookError, e:
                path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
                self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working"})) 
            
        
        
class MyState(webapp.RequestHandler):
    def post(self):
        try:
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self)
            if self.facebookapi is None:
                return
            
            user = self.facebookapi.users.getInfo([self.facebookapi.uid], ['uid', 'name', 'current_location'])[0]
            userInfo = dbUtil().getLegislatorForUser(user["uid"], user["current_location"], True)
            if userInfo is None:
                self.response.out.write('<fb:redirect url="/representedby/location" />')
            else: 
                userInfo["rep"] = None
                userInfo["section"] = "mystate"
                userInfo["discussion_board"] = {"id": userInfo["state"], "name": "your state", "modifier": "in"}
                userInfo["loggedin"] = True
                output = PageCreator()
                output.render(self, userInfo)
                
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working"}))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)}))
         
        
        
class MyDistrict(webapp.RequestHandler):
    def post(self):  
        try:
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self)
            if self.facebookapi is None:
                return
            
            user = self.facebookapi.users.getInfo([self.facebookapi.uid], ['uid', 'name', 'current_location'])[0]
            userInfo = dbUtil().getLegislatorForUser(user["uid"], user["current_location"], True)
            if userInfo is None:
                self.response.out.write('<fb:redirect url="/representedby/location" />')
            else: 
                userInfo["jrsen"] = None
                userInfo["srsen"] = None
                if userInfo.has_key("rep"):
                    userInfo["discussion_board"] = {"id": userInfo["rep"], "name": "your district", "modifier": "in"}
                else:
                    userInfo["discussion_board"] = {"id": "", "name": "your district", "modifier": "in"}
                userInfo["section"] = "mydistrict"
                userInfo["loggedin"] = True
                output = PageCreator()
                output.render(self, userInfo)
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working"}))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)})) 
          
          
          
class PageCreator():
    def render(self, webapp, userInfo=None):
        
        path = os.path.join(os.path.dirname(__file__), '../templates/heading.fbml')
        webapp.response.out.write(template.render(path, userInfo))
        
        legislator_keys = ["rep", "jrsen", "srsen", "legislator"]
        legislators = {"legislators":[], "flags": {"official_rss": [], "twitter_id": [], "youtube_url": [], "newsfeed": False, "discussion_board": userInfo["discussion_board"]}}
        sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)

        if userInfo is not None:
            if userInfo["section"] == "main":
                legislators["flags"]["newsfeed"] = True
            legislators["discussion_board"] = userInfo["discussion_board"]
            legislators["loggedin"] = userInfo["loggedin"]
            for title in legislator_keys:
                if userInfo.has_key(title):
                    if userInfo[title] is not None:
                        if userInfo[title] == "BLANK":
                            fakeLegislator = {"blank": True, "bioguide_id": "BLANK", "title": "Rep"}
                            legislators["legislators"].append( fakeLegislator )
                        else:
                            response = sunlight.apicall('legislators.get', {"bioguide_id": userInfo[title]})
                            if response is not None:
                                if response.has_key("legislator"):
                                    #check to see if they have an official RSS, Twitter, or YouTube page
                                    for key in legislators["flags"].keys():               
                                        if response["legislator"].has_key(key):
                                            if response["legislator"][key] is not None:
                                                if len(response["legislator"][key]):
                                                    legislators["flags"][key].append(userInfo[title])
                                    
                                    response["legislator"]["friendly_name"] = const.FRIENDLY_NAME[userInfo[title]]                
                                    legislators["legislators"].append( response["legislator"] )
                                        
                                    
        if len(legislators["legislators"]) == 0:
            # user doesn't have any legislators, ask them to pick their location
            webapp.response.out.write('<fb:redirect url="/representedby/location" />')
            return
        else:
            
            if userInfo["loggedin"]:
                
                if userInfo["section"] == "main":
                    path = os.path.join(os.path.dirname(__file__), '../templates/profile.fbml')
                    profileFBML = webapp.facebookapi.profile.setFBML(None, webapp.facebookapi.uid, None, None, None, template.render(path, legislators))
                friends_in_area = Set()
                friends_with_app_ids = webapp.facebookapi.friends.getAppUsers()
                
                results = []
                if friends_with_app_ids is not None:
                    if len(friends_with_app_ids) > 0:
                        for friend in friends_with_app_ids:
                            query = UserDistrict.all()
                            query.filter("uid =", int(friend))
                            results = query.fetch(1)
                
                            for result in results:
                                if userInfo.has_key("legislator"):
                                    if result.rep:
                                        if userInfo["legislator"] == result.rep:
                                            friends_in_area.add(result.uid)
                                    if result.jrsen:
                                        if userInfo["legislator"] == result.jrsen:
                                            friends_in_area.add(result.uid)
                                    if result.srsen:
                                        if userInfo["legislator"] == result.srsen:
                                            friends_in_area.add(result.uid)    
                                    
                                else:
                                    if result.rep:
                                        if userInfo.has_key("rep"):
                                            if userInfo["rep"] == result.rep:
                                                friends_in_area.add(result.uid)
                                    if result.jrsen:
                                        if userInfo.has_key("jrsen"):
                                            if userInfo["jrsen"] == result.jrsen:
                                                friends_in_area.add(result.uid)
                                    if result.srsen:
                                        if userInfo.has_key("srsen"):
                                            if userInfo["srsen"] == result.srsen:
                                                friends_in_area.add(result.uid)          
            
                friendList = webapp.facebookapi.users.getInfo(list(friends_in_area), ['uid', 'name']) 
                legislators["friends"] = friendList

                
            if (userInfo["section"] == "legislators"):
                path = os.path.join(os.path.dirname(__file__), '../templates/legislator.fbml') 
            else:      
                path = os.path.join(os.path.dirname(__file__), '../templates/column_right.fbml')
            webapp.response.out.write(template.render(path, legislators))
            
            
            if webapp.request.get('v', default_value=None) == "2":
                path = os.path.join(os.path.dirname(__file__), '../templates/column_left_v2.fbml')    
            else:
                path = os.path.join(os.path.dirname(__file__), '../templates/column_left.fbml')     
            webapp.response.out.write(template.render(path, legislators))
            
                 
def main():
	application = webapp.WSGIApplication([('/fb/', MainHandler),('/fb/legislator', Legislator),('/fb/district', MyDistrict),('/fb/state', MyState)],
									   debug=True)
	run_wsgi_app(application)
									   

webapp.template.register_template_library('customfilters')
if __name__ == '__main__':
	main()
